import dynamic from 'next/dynamic'
import Footer from '@c/footer'
import Responsive from '@c/responsive'
import Button from '@c/button'
import Image from '@c/image'
import styles from './index.module.scss'
import {  getActorInfoBySearch } from '@/api/vod'
import { getSearchData } from '@/api/home'
import cm from 'classnames'
import { useState, useEffect } from 'react'
import { useRouter } from 'next/router'
import Link from 'next/link'
import Loading from '@c/request-loading'

const Null = dynamic(() => import('@c/null'))

const formatList = data => {
  if (!data) {
    return []
  }
  return data.map(item => {
    item.renderLabel = [item.chname, ...(Array.isArray(item.label) ? item.label : [item.label])]
    return item
  })
}

// 搜索任务DOM
const PersonList = props => {
  const { data, word } = props
  return (
    <>
      {data?.persons?.slice(0, 3)?.map((item, index) => {
        try {
          item.info = JSON.parse(item.info)
        } catch (error) {}
        return (
          <div
            key={index}
            className={cm({
              [styles.actorInfo]: true,
              [styles.actorInfoLast]: index + 1 === data?.persons?.length
            })}
          >
            <Image className={styles.actorHead} src={item.headPic} alt={word} />
            <div>
              <Link href={`/person/${item.id}`} className={styles.name}>
                {item.name}
              </Link>
              <p className={styles.info}>{item.info}</p>
              <Button className={styles.actorDetail} link href={`/person/${item.id}`}>
                <img loading="lazy" src="/images/h-detail.png" alt="详情" />
                <span>查看详情</span>
              </Button>
            </div>
          </div>
        )
      })}
    </>
  )
}

const Index = () => {
  const router = useRouter()
  const { asPath, query } = router
  const { word } = query
  const [list, setList] = useState(null)
  const [total, setTotal] = useState(0)
  const [actorInfo, setActorInfo] = useState({})
  const initData = async () => {
    const resArr = (
      await Promise.all([getSearchData({ word, page: 1, pageSize: 12 }, {}), getActorInfoBySearch(word, {})])
    ).map(item => {
      if (item.code === 0) {
        return item.data || {}
      }
      return {}
    })
    setList(formatList(resArr[0].list))
    setTotal(resArr[0].total)
    setActorInfo(resArr[1])
  }
  useEffect(() => {
    setList(null)
    setActorInfo({})
    setTotal(0)
    initData()
  }, [asPath])

  useEffect(() => {
    return () => {
      sessionStorage.setItem('lastPage', true)
    }
  }, [])

  return (
    <Responsive className={cm(styles.searchContainer, styles.searchContainerPhone)} needHidden>
      <PersonList data={actorInfo} word={word} />
      {list && (
        <div className={styles.title}>
          <h1 className={styles.searchText}>“{word}”</h1>
          <span className={styles.searchTip}>
            已为您搜索到<span>{total}</span>部相关影视内容
          </span>
        </div>
      )}
      <div className={styles.filterItem}>
        {!list ? (
          <div className={styles.loading}>
            <Loading width={30} />
          </div>
        ) : !list.length ? (
          <Null />
        ) : (
          list.map(item => {
            return (
              <div key={item.id} className={styles.item}>
                <Image alt={item.name} src={item.posterUrl} className={styles.poster} />
                <div className={styles.mask}></div>
                <div className={styles.info}>
                  <div className={styles.markBox}>
                    {item.tmdbScore ? (
                      <div className={styles.mark}>
                        <img loading="lazy" src="/images/tmdb.png" alt="tmdb" className={styles.tmdb} />
                        <span>{('' + item.tmdbScore).toFix(1)}</span>
                      </div>
                    ) : null}
                    {item.doubanScore ? (
                      <div className={styles.mark}>
                        <img loading="lazy" src="/images/douban.png" alt="douban" className={styles.douban} />
                        <span>{('' + item.doubanScore).toFix('')}</span>
                      </div>
                    ) : null}
                  </div>
                  <Link href={`/vod/detail/${item.id}`} className={cm(styles.infoName, 'textEllipsis')}>
                    {item.name}
                  </Link>
                  <div className={styles.infoTag}>{item.renderLabel.join('，')}</div>
                  <p className={styles.infoCount}>
                    <span>{item.time}</span>
                    <span>{item.playTime}</span>
                  </p>
                  <p className={styles.infoDesc}>{item.desc}</p>
                  <Button className={styles.btn} link href={`/vod/play-official/${item.id}/1`}>
                    <img loading="lazy" src="/images/h-play.png" alt="播放" />
                    <span>播放</span>
                  </Button>
                  <Button className={cm(styles.btn, styles.btnDetail)} link href={`/vod/detail/${item.id}`}>
                    <img loading="lazy" src="/images/h-detail.png" alt="详情" />
                    <span>查看详情</span>
                  </Button>
                </div>
              </div>
            )
          })
        )}
      </div>

      <Footer />
    </Responsive>
  )
}
export default Index

export async function getServerSideProps({ query }) {
  const { word = '' } = query

  return {
    props: {
      layoutProps: {
        noSomeMetaInfo: false,
        title: '搜索结果：' + word
      }
    }
  }
}
